# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: shell_limit_cpumem.py 
@time: 2019/8/2 下午3:08
@note:
在unix或linux限制cpu或内存
"""
import signal
import resource
import os
import time

'限制cpu 15秒'
def time_exceeded(signo, frame):

    print("Time's up!")
    raise SystemExit(1)

def set_max_runtime(seconds):

    soft, hard = resource.getrlimit(resource.RLIMIT_CPU)
    resource.setrlimit(resource.RLIMIT_CPU, (seconds, hard))
    signal.signal(signal.SIGXCPU, time_exceeded)

'限制内存'
def limit_memory(maxsize):

    soft, hard = resource.getrlimit(resource.RLIMIT_AS)
    resource.setrlimit(resource.RLIMIT_AS, (maxsize, hard))


if __name__ == '__main__':

    set_max_runtime(15)

    while True:
        limit_memory(1)


